package com.sagereal.wtc.factorymode.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseManager {
    private DatabaseHelper dbHelper;
    private SQLiteDatabase database;

    public DatabaseManager(Context context) {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
    }

    public void saveResult(String itemName, String status, String itemCheck) {
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_ITEM_NAME, itemName);
        values.put(DatabaseHelper.COLUMN_STATUS, status);
        values.put(DatabaseHelper.COLUMN_CHECK, itemCheck);

        // 尝试更新现有行，如果不存在则插入新行
        int rowsUpdated = database.update(DatabaseHelper.TABLE_NAME, values,
                DatabaseHelper.COLUMN_CHECK + " = ?", new String[]{itemCheck});

        if (rowsUpdated == 0) {
            database.insert(DatabaseHelper.TABLE_NAME, null, values);
        }
    }

    public String getResult(String itemCheck) {
        String status = "";
        String[] columns = {DatabaseHelper.COLUMN_STATUS};
        String selection = DatabaseHelper.COLUMN_CHECK + " = ?";
        String[] selectionArgs = {itemCheck};

        Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, selection, selectionArgs,
                null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            status = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_STATUS));
            cursor.close();
        }
        return status;
    }



    public void close() {
        database.close();
        dbHelper.close();
    }
}
